#_*_ coding: UTF-8 _*_

from core import uicomponents, db, log, constants
from PyQt4 import QtGui, QtCore
from servers.quran.quran_window import *
import servers.page_number.definitions
import servers.quran.definitions
import servers.quran.ui

class QuranBrowser(QtGui.QMainWindow):
	def __init__(self, parent=None):
		QtGui.QMainWindow.__init__(self, parent)

		self.searchdlg = QuranAdvancedSearchDialog(self)

		searchAction = QtGui.QAction(QtGui.QIcon(constants.app_path+'\images\search.gif'), u'جستجو', self)
		searchAction.setShortcut('Ctrl+F')
		searchAction.setStatusTip(u'جستجو در آیات قرآن')
		QtCore.QObject.connect(searchAction, QtCore.SIGNAL("triggered()"), self.startASearch)
		
		asearchAction = QtGui.QAction(QtGui.QIcon(constants.app_path+'\images\search.gif'), u'جستجوی پیشرفته', self)
		asearchAction.setShortcut('Ctrl+Alt+F')
		asearchAction.setStatusTip(u'جستجو در آیات قرآن به صورت قوی')
		QtCore.QObject.connect(asearchAction, QtCore.SIGNAL("triggered()"), self.startAAdvancedSearch)

		searchMenu = self.menuBar().addMenu(u'جستجو')
		searchMenu.addAction(searchAction)
		searchMenu.addAction(asearchAction)

		self.menuBar().addMenu(uicomponents.SharedUi.modulesListMenu)

		self.quran = QuranMainView()
		self.quran.gotoSafhe(1)
		self.setMainView(self.quran)

	def addWordMenus(self):
		matnViewMenu = self.menuBar().addMenu(u'متن قرآن')
		matnMasksMenu = matnViewMenu.addMenu(u'کلمات قرآن')
		self.quranMaskActions={}
		for mask in servers.quran.definitions.quranWordMasks:
			self.quranMaskActions[mask] = QtGui.QAction(unicode(mask,"utf-8"),self)
			self.quranMaskActions[mask].setCheckable(True)
			self.quranMaskActions[mask].setChecked(False)
			QtCore.QObject.connect(self.quranMaskActions[mask],QtCore.SIGNAL("triggered()"),self.changeMask)
			matnMasksMenu.addAction(self.quranMaskActions[mask])

		matnCommentMenu = matnViewMenu.addMenu(u'توضيحات')
		self.quranCommenterActions={}
		for commenter in servers.quran.definitions.quranWordCommenters:
			self.quranCommenterActions[commenter] = QtGui.QAction(unicode(commenter,"utf-8"),self)
			self.quranCommenterActions[commenter].setCheckable(True)
			self.quranCommenterActions[commenter].setChecked(False)
			QtCore.QObject.connect(self.quranCommenterActions[commenter],QtCore.SIGNAL("triggered()"),self.changeCommenter)
			matnCommentMenu.addAction(self.quranCommenterActions[commenter])

	def changeMask(self):
		servers.quran.definitions.quranWordViewMasks = []
		for maskAction in self.quranMaskActions:
			if self.quranMaskActions[maskAction].isChecked():
				servers.quran.definitions.quranWordViewMasks.append(maskAction)
		servers.quran.ui.quranBrowser.quran.refreshWithPath()		

	def changeCommenter(self):
		servers.quran.definitions.quranWordViewCommenters = []
		for commenterAction in self.quranCommenterActions:
			if self.quranCommenterActions[commenterAction].isChecked():
				servers.quran.definitions.quranWordViewCommenters.append(commenterAction)
		servers.quran.ui.quranBrowser.quran.refreshWithPath()		

	def setMainView(self, mvView):
		self.setCentralWidget(mvView)


	def startAAdvancedSearch(self):
		res = self.searchdlg.show()
		if res!=QtGui.QDialog.Accepted:
			return
		
		uicomponents.SharedUi.busyDialog.tellBusy(u'لطفا چند لحظه صبر کنید...')
		expression = self.searchdlg.getSearchParams()
		ayatWithHighlight = Quran.findAdvancedAyat(unicode(expression))


		quranSearchResult.showAyat(ayatWithHighlight)
		uicomponents.SharedUi.busyDialog.tellDone()
		
	def startASearch(self):
		searchdlg = QuranSearchDialog(self)
		res = searchdlg.show()
		if res!=QtGui.QDialog.Accepted:
			return
		
		uicomponents.SharedUi.busyDialog.tellBusy(u'لطفا چند لحظه صبر کنید...')
		expression, wholeWord, withErab, quranScope = searchdlg.getSearchParams()
		if (quranScope):
			ayatWithHighlight = Quran.findAyat(unicode(expression), Quran.getSoorehByNumber(1), None, Quran.getSoorehByNumber(114), None, withErab, wholeWord) #TODO: correct this and replace Nones
		else:
			soorehAyat = self.quran.sooreh.ayat
			ayatWithHighlight = Quran.findAyat(unicode(expression), self.quran.sooreh, soorehAyat[0], self.quran.sooreh, soorehAyat[-1], withErab, wholeWord)
		
		quranSearchResult.showAyat(ayatWithHighlight)
		uicomponents.SharedUi.busyDialog.tellDone()


class QuranSearchResult(QtGui.QMainWindow):
	def __init__(self, parent=None):
		QtGui.QMainWindow.__init__(self, parent)
		self.resultView = QuranSearchResultView(qBrowser=quranBrowser)

	def showAyat(self,HighlightedAyat):
		showResults()
		self.resultView.showResults(HighlightedAyat)
		self.setCentralWidget(self.resultView)


def showView():
	uicomponents.SharedUi.mainWindow.addDockWidget(QtCore.Qt.TopDockWidgetArea,uicomponents.SharedUi.applications['quran']['docables']['quranBrowser'])
	uicomponents.SharedUi.applications['quran']['docables']['quranBrowser'].widget().addWordMenus()
	uicomponents.SharedUi.applications['quran']['docables']['quranBrowser'].show()



def showResults():
	if not uicomponents.SharedUi.applications['quran']['docables']['quranSearchResult'].isVisible():
		uicomponents.SharedUi.mainWindow.addDockWidget(QtCore.Qt.BottomDockWidgetArea,uicomponents.SharedUi.applications['quran']['docables']['quranSearchResult'])
		uicomponents.SharedUi.applications['quran']['docables']['quranSearchResult'].show()	



uicomponents.SharedUi.applications['quran']  = {}
uicomponents.SharedUi.applications['quran']['actionSlot'] = showView
uicomponents.SharedUi.applications['quran']['name']  = u'قرآن'
uicomponents.SharedUi.applications['quran']['shortcut'] = u'Ctrl+Q'
uicomponents.SharedUi.applications['quran']['docables']={}
uicomponents.SharedUi.applications['quran']['docables']['quranBrowser'] = QtGui.QDockWidget(uicomponents.SharedUi.mainWindow)
uicomponents.SharedUi.applications['quran']['docables']['quranBrowser'].setWindowTitle(u'نمايش قرآن')
uicomponents.SharedUi.applications['quran']['docables']['quranBrowser'].resize(500,100)
quranBrowser = QuranBrowser()
uicomponents.SharedUi.applications['quran']['docables']['quranBrowser'].setWidget(quranBrowser)
uicomponents.SharedUi.applications['quran']['docables']['quranBrowser'].hide()

uicomponents.SharedUi.applications['quran']['docables']['quranSearchResult'] = QtGui.QDockWidget(uicomponents.SharedUi.mainWindow)
uicomponents.SharedUi.applications['quran']['docables']['quranSearchResult'].setWindowTitle(u'نتايج جستجو')
uicomponents.SharedUi.applications['quran']['docables']['quranSearchResult'].resize(500,100)
quranSearchResult = QuranSearchResult()
uicomponents.SharedUi.applications['quran']['docables']['quranSearchResult'].setWidget(quranSearchResult)
uicomponents.SharedUi.applications['quran']['docables']['quranSearchResult'].hide()


def changeAdvanceSearchQueryQPath():
	query = unicode(servers.quran.definitions.advSearchQuery['widget'].text())
	q = ""
	if advancedSearchResultType.currentIndex()==1:
		q = "s:"
	if advancedSearchResultType.currentIndex()==2:
		q = "a:"
	if advancedSearchResultType.currentIndex()==3:
		q = "w:"
	sureQ = unicode(advancedSearchSureQuery.text()).strip()	
	if len(sureQ) == 0:
		q += "*/"
	else:
		q += sureQ + "/"
	ayeQ = unicode(advancedSearchAyeQuery.text()).strip()	
	if len(ayeQ) == 0:
		q += "*/ "
	else:	
		q += ayeQ +"/ "

	query = q

	servers.quran.definitions.advSearchQuery['widget'].setText(query)



servers.quran.definitions.advSearchPlugins['qpath'] = {}
servers.quran.definitions.advSearchPlugins['qpath']['layout'] = QtGui.QVBoxLayout()
servers.quran.definitions.advSearchPlugins['qpath']['layout'].addWidget(QtGui.QLabel(u'نمايش نتيجه در قالب'))
advancedSearchResultType = QtGui.QComboBox()
advancedSearchResultType.addItem(u'پيش فرض')
advancedSearchResultType.addItem(u'سوره')
advancedSearchResultType.addItem(u'آيه')
advancedSearchResultType.addItem(u'کلمه')
servers.quran.definitions.advSearchPlugins['qpath']['layout'].addWidget(advancedSearchResultType)
servers.quran.definitions.advSearchPlugins['qpath']['layout'].addWidget(QtGui.QLabel(u'سوره:'))
servers.quran.definitions.advSearchPlugins['qpath']['layout'].addWidget(QtGui.QLabel(u'مثلا:2 يا 5-10 يا حمد يا ب*ه يا ...'))
advancedSearchSureQuery = QtGui.QLineEdit()
servers.quran.definitions.advSearchPlugins['qpath']['layout'].addWidget(advancedSearchSureQuery)
servers.quran.definitions.advSearchPlugins['qpath']['layout'].addWidget(QtGui.QLabel(u'آيه:'))
servers.quran.definitions.advSearchPlugins['qpath']['layout'].addWidget(QtGui.QLabel(u'مثلا:2 يا 5-10 يا *سَلامٌ* يا N*سلام* يا ...'))
advancedSearchAyeQuery = QtGui.QLineEdit()
servers.quran.definitions.advSearchPlugins['qpath']['layout'].addWidget(advancedSearchAyeQuery)

QtCore.QObject.connect(advancedSearchResultType,QtCore.SIGNAL("currentIndexChaned(int)"),changeAdvanceSearchQueryQPath)
QtCore.QObject.connect(advancedSearchSureQuery,QtCore.SIGNAL("textChanged(QString)"),changeAdvanceSearchQueryQPath)
QtCore.QObject.connect(advancedSearchAyeQuery,QtCore.SIGNAL("textChanged(QString)"),changeAdvanceSearchQueryQPath)

print "Quran Ui Components Added"
